package com.vineetmanohar.maventwitter;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;

import twitter4j.RateLimitStatus;
import twitter4j.Twitter;
import twitter4j.TwitterException;

/**
 * Sends a message to Twitter
 * 
 * @requiresOnline true
 * @goal tweet
 * @author Vineet Manohar
 */
public class TweetMojo extends AbstractMojo {
	/**
	 * The text that you want to set as your Twitter status
	 * 
	 * @since 0.1
	 * @required
	 * @parameter expression="${twitterStatus}"
	 */
	private String twitterStatus;

	/**
	 * Your Twitter account username
	 * 
	 * @since 0.1
	 * @required
	 * @parameter expression="${twitterUsername}"
	 */
	private String twitterUsername;

	/**
	 * Your Twitter account password
	 * 
	 * @since 0.1
	 * @required
	 * @parameter expression="${twitterPassword}"
	 */
	private String twitterPassword;

	public void execute() throws MojoExecutionException {
		try {
			try {
				String calculatedStatus = tweet(twitterUsername,
						twitterPassword, twitterStatus);
				getLog().info("Twitter status update: " + calculatedStatus);
			} catch (TwitterHourlyQuotaExhausted e) {
				getLog().error(e.getMessage(), e);
			}
		} catch (TwitterException e) {
			throw new MojoExecutionException(
					"Twitter twitterStatus update failed: " + e.getMessage(), e);
		}
	}

	static String tweet(String twitterUsername, String twitterPassword,
			String twitterStatus) throws TwitterException,
			TwitterHourlyQuotaExhausted {
		Twitter twitter = new Twitter(twitterUsername, twitterPassword);

		// source, this will show up as "from web" since Twitter no longer
		// allows people to set source via non-Oauth
		twitter.setSource("Maven");

		RateLimitStatus rateLimitStatus = twitter.rateLimitStatus();

		if (rateLimitStatus.getRemainingHits() == 0) {
			throw new TwitterHourlyQuotaExhausted(rateLimitStatus);
		}

		String calculatedStatus = getCalculatedStatus(twitterStatus);

		twitter.updateStatus(calculatedStatus);

		return calculatedStatus;
	}

	/**
	 * Shorten status if needed.
	 * 
	 * TODO: implement status shortening
	 * 
	 * @param twitterStatus
	 * @return
	 */
	private static String getCalculatedStatus(String twitterStatus) {
		return twitterStatus;
	}
}